﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;

namespace G.APITest.Controls
{
    public partial class EditePluginControl : UserControl
    {
        public EditePluginControl()
        {
            InitializeComponent();
            listbox.ItemsSource = Utils.ExtendPageUtiles.AppPluginInfos;
        }

        private void setuppanel_Expanded(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            GloabalData.Instance.SampleClient.Execute(new Service.API.Request.GetAppPluginAddressRequest(), (c) =>
            {
                listboxsetup.ItemsSource = c.ResponseData;
            });
        }
        [System.ComponentModel.Composition.Import(typeof(G.SL.Part.IPlugin))]
        public G.SL.Part.IPlugin PlugIn { get; set; }
        private void btnSetup_Click(object sender, RoutedEventArgs e)
        {
            FrameworkElement f = sender as FrameworkElement;
            string str = f.DataContext as string;
            string url = String.Format("{0}/{1}?t={2}", G.Service.API.APIConfig.BaseUrl, str,DateTime.Now.GetTimestamp());
            WebClient client = new WebClient();
            client.OpenReadCompleted += (s, _e) =>
            {
                if (_e.Error == null)
                {
                    try
                    {
                        var buffer = _e.Result.GetBytes();
                        _e.Result.Seek(0, SeekOrigin.Begin);
                        this.PlugIn = null;
                        Utils.MEFUtils.LoadPart(_e.Result, this);
                        if (this.PlugIn == null)
                        {
                            throw new Exception("");
                        }
                        Utils.ExtendPageUtiles.AddPlugin(buffer, url, this.PlugIn.Name);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("加载的DLL无效！无可装配的有效对象\r\n" + ex.Message);
                    }
                }
            };
            client.OpenReadAsync(new Uri(url));
        }

        private void deletePlugin_Click(object sender, RoutedEventArgs e)
        {
            FrameworkElement f = sender as FrameworkElement;
            G.APITest.Data.APPPluginInfo p = f.DataContext as G.APITest.Data.APPPluginInfo;
            Utils.ExtendPageUtiles.DeletePlugin(p);
        }
    }
}
